package top.tresman.cxxcommon.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import top.tresman.cxxcommon.annotation.EnumRule;
import top.tresman.cxxcommon.contract.EnumValueProvider;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class EnumValidator implements ConstraintValidator<EnumRule, Integer> {
    private Set<Integer> allowedValues;

    @Override
    public void initialize(EnumRule constraintAnnotation) {
        Class<? extends EnumValueProvider> enumClass = constraintAnnotation.value();
        allowedValues = Arrays.stream(enumClass.getEnumConstants())
                .map(EnumValueProvider::getValue)
                .collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null) {
            return true; // 配合@NotNull使用
        }
        return allowedValues.contains(value);
    }
}
